package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.dataSource.DataSourceKeyUtil;
import com.bestv.search.common.model.UserAccessDetail;
import com.bestv.search.common.service.UserAccessDetailManager;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * @author Justin Luo
 */
public class UserAccessDetailCommand {

    private Logger logger = Logger.getLogger(UserAccessDetailCommand.class);
    private UserAccessDetailManager userAccessDetailManager;

    public void saveUserAccessDetailList(List<UserAccessDetail> list, String siteCode) {

        logger.info("Save UserAccessDetail list into DB started :" + list.size());

        DataSourceKey key = DataSourceKeyUtil.convert(siteCode);
        userAccessDetailManager.saveOrUpdateUserAccessDetailList(key, list);

        logger.info("Save UserAccessDetail list into DB finished.");
    }

    public List<UserAccessDetail> getUserAccessDetails(String filePath) {
        BufferedReader br = null;
        HashMap<String, UserAccessDetail> results = new HashMap<String, UserAccessDetail>();
        try {
            br = new BufferedReader(new FileReader(filePath));
            String line;
            // each row is one search record
            while ((line = br.readLine()) != null) {
                UserAccessDetail record = new UserAccessDetail();

                // each row have four columns, they are dataTime, keyword,
                // userId, domain and split by ","
                String[] fields = line.split(",");
                String dateStr = fields[0].split(" ")[0];
                record.setDate(convert(dateStr));
                record.setUserId(fields[2]);
                record.setSearchCount(1);
                record.setInsertTime(new Date());
                record.setDomain(fields[3]);

                // Checks record whether exist in result map.
                UserAccessDetail recordInMap = results.get(record.getUserId());
                if (recordInMap == null) {
                    // doesn't exist, add record to results map.
                    results.put(record.getUserId(), record);
                } else {
                    // exists, update the count
                    recordInMap.setSearchCount(recordInMap.getSearchCount() + 1);
                }
            }
        } catch (IOException e) {
            logger.error("Gets SearchKeywordHistoryList failed form file : " + filePath);
            logger.error(e);
            e.printStackTrace();
        } finally {
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        // Convert to list
        UserAccessDetail[] details = new UserAccessDetail[results.values().size()];
        return Arrays.asList(results.values().toArray(details));
    }

    private Date convert(String dateStr) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Integer.valueOf(dateStr.substring(0, 4)), Integer.valueOf(dateStr.substring(5, 7)) - 1,
                Integer.valueOf(dateStr.substring(8)));
        return calendar.getTime();
    }

    public UserAccessDetailManager getUserAccessDetailManager() {
        return userAccessDetailManager;
    }

    public void setUserAccessDetailManager(UserAccessDetailManager userAccessDetailManager) {
        this.userAccessDetailManager = userAccessDetailManager;
    }
}